<?php

class FormAction_Images extends FormAction
{

  public $fields = array('filename' => 'image_filename', 'caption' => 'image_caption', 'width' => 'image_width', 'height' => 'image_height');

  protected $action = Form::ACTION_IMAGES;

  public function execute()
  {
    if (s::request()->get('formAction') == 'galleryThumb') {
      $file = s::request()->get('file');

      $thumb = $this->getThumbComponent();
      $thumb->setParam('config_cache_directory', $this->getCacheDir());
      $thumb->setParam('config_document_root', $this->getFilesDir());
      $thumb->parse($file);

      echo $thumb->output(100, 100);

      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesCheckUpload') {
      $data = array();
      $view = View::factory('Json');
      $view->copyAll($data);
      echo $view->render();
      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesUpload') {
      $data = array();

      if (! empty($_FILES['Filedata'])) {
        try {
          $upload = Component::factory('upload');
          $upload->getParameters()->set('hash_filename', true);
          $upload->upload('Filedata');

          $row = array(
            $this->fields['filename'] => $upload->getUploadedPath()
          );

          foreach ($this->form->getFilters() as $filter) {
            $filter->setDataFromPost($row, s::request()->post(), Form::ACTION_CREATE);
          }

          $this->gateway()->save($row);

          //$image[$this->getPrimaryKey()] = DB::getInstance()->lastInsertId();

          //$image['thumb_src'] = $this->getThumb($image[$this->getFieldName('filename')], 100, 100);
          //$image['image_src'] = $this->getThumb($image[$this->getFieldName('filename')]);

          $data['image'] = $row;
        }
        catch (Exception $e) {
          $data['error'] = $e->getMessage();
        }
      }

      $view = View::factory('Json');
      $view->copyAll($data);
      echo $view->render();
      exit();
    }

    $this->loadData();
  }

  public function render()
  {
    $this->set('uploadScript', s::makeUrl($route, false));
    $this->set('uploadScriptData', json_encode(array_merge(s::response()->getParams()->getAll(), array('formAction' => 'imagesUpload', 'sid' => session_id()))));

    return parent::render();
  }

  protected function loadData()
  {
    $params = array();

    $params['fields'] = array($this->form->pk);
    $params['where'] = array();
    $params['data'] = array();

    foreach ($this->form->getFilters() as $filter) {
      $filter->injectQueryParams($params);
    }

    $elements = $this->form->getElements($this->action);
    while ($element = $elements->next()) {
      $element->injectQueryParams($params);
    }

    $params['fields'] = array_filter(array_unique($params['fields']));

    $data = $this->gateway()->findAll($params);

    foreach ($data as &$row) {
      $this->filterDbData($row, $this->action);

      $row['thumb_src'] = $this->getThumb($row[$this->fields['filename']], 100, 100, array('zc' => 1));
      $row['image_src'] = $this->getThumb($row[$this->fields['filename']]);
      $row['image_caption'] = $row[$this->fields['caption']];
    }

    $this->formData = $data;
  }

  protected function getThumb($file, $width = null, $height = null, $params = null)
  {
    try {
      if (! file_exists($this->getFilesDir() . $file)) {
        $src = false;
      }

      if ($width && $height) {
        $thumb = $this->getThumbComponent();

        $thumb->setParam('config_cache_directory', $this->getCacheDir());
        $thumb->setParam('config_document_root', $this->getFilesDir());

        foreach ((array)$params as $param => $value) {
          $thumb->setParam($param, $value);
        }

        $thumb->parse($file);

        $src = $this->getCacheUrl() . '/' . $thumb->getCacheFilename($width, $height);
      }
      else {
        $src = $this->getFilesUrl() . $file;
      }
    }
    catch (Exception $e) {
      $src = false;
    }

    return $src;
  }

  protected function getFilesUrl()
  {
    return s::config()->get('files_url');
  }

  protected function getCacheUrl()
  {
    return s::config()->get('files_url') . '/cache';
  }

  protected function getFilesDir()
  {
    return s::config()->get('files_dir');
  }

  protected function getCacheDir()
  {
    return s::config()->get('files_dir') . '/cache';
  }

  /**
   *
   * @return PhpThumbComponent
   */
  protected function getThumbComponent()
  {
    return Component::factory('php_thumb');
  }

}
